package com.chenjim.glrecorder.surfacetexture;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.util.Size;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Camera2PreviewActivity extends Activity {
    private CameraGLSurfaceView mGLSurfaceView;
    private String mCameraId;
    private CameraDevice mCameraDevice;
    private CameraCaptureSession mCaptureSession;
    private CameraManager mCameraManager;
    private Handler mBackgroundHandler;
    private HandlerThread mBackgroundThread;
    private Button mButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 创建一个 LinearLayout，设置为竖直方向排列
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);  // 设置竖直排列
        //        layout.setPadding(16, 16, 16, 16);  // 设置内边距

        // 创建 CameraGLSurfaceView
        mGLSurfaceView = new CameraGLSurfaceView(this);
        LinearLayout.LayoutParams glParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f);  // 竖直方向占据剩余空间
        mGLSurfaceView.setLayoutParams(glParams);

        // 创建按钮
        mButton = new Button(this);
        mButton.setText("点击预览");
        LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mButton.setLayoutParams(buttonParams);

        // 将 CameraGLSurfaceView 和按钮添加到布局中
        layout.addView(mGLSurfaceView);
        layout.addView(mButton);

        setContentView(layout);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            // 请求摄像头权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    0);
        }

        mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        mGLSurfaceView.setOnClickListener(v -> {
            mGLSurfaceView.setSuperResolutionUniform(mButton);
        });

        // 设置按钮点击事件
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 在这里处理按钮点击事件
                Log.i(this.getClass().getSimpleName(), "setOnClickListener");
                if (mGLSurfaceView.getSurfaceTexture() != null) {
                    Log.i(this.getClass().getSimpleName(), "setOnClickListener");
                    openCamera();
                } else {
                    Log.i(this.getClass().getSimpleName(), "setOnClickListener null");
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        startBackgroundThread();
        mGLSurfaceView.onResume();

    }

    @Override
    protected void onPause() {
        closeCamera();
        stopBackgroundThread();
        mGLSurfaceView.onPause();
        super.onPause();
    }

    private void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("CameraBackground");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }

    private void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void openCamera() {
        try {
            // 选择后置摄像头
           /* for (String cameraId : mCameraManager.getCameraIdList()) {
                CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
                if (characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) {
                    mCameraId = cameraId;
                    break;
                }
            }*/

            String[] cameraIdList = mCameraManager.getCameraIdList();

            Log.d(this.getClass().getSimpleName(), "camera list: " + Arrays.toString(cameraIdList));
            mCameraId = cameraIdList[0];

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                // 请求权限
                // 请求摄像头权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CAMERA},
                        0);
                return;
            }

            mCameraManager.openCamera(mCameraId, new CameraDevice.StateCallback() {
                @Override
                public void onOpened(@NonNull CameraDevice camera) {
                    mCameraDevice = camera;
                    createCameraPreviewSession();
                }

                @Override
                public void onDisconnected(@NonNull CameraDevice camera) {
                    camera.close();
                    mCameraDevice = null;
                }

                @Override
                public void onError(@NonNull CameraDevice camera, int error) {
                    camera.close();
                    mCameraDevice = null;
                }
            }, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private void createCameraPreviewSession() {
        try {
            SurfaceTexture texture = mGLSurfaceView.getSurfaceTexture();
            if (texture == null) {
                return;
            }

            // 获取最佳预览尺寸
            StreamConfigurationMap map = mCameraManager
                    .getCameraCharacteristics(mCameraId)
                    .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            Size[] sizes = map.getOutputSizes(SurfaceTexture.class);
            Size previewSize = chooseBestSize(sizes);

            // 设置缓冲区大小
            texture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight());
            Surface surface = new Surface(texture);

            // 创建预览请求
            final CaptureRequest.Builder previewRequestBuilder =
                    mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            previewRequestBuilder.addTarget(surface);

            // 设置自动对焦模式
            previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

            // 创建捕获会话
            List<Surface> surfaces = Collections.singletonList(surface);
            mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession session) {
                    if (mCameraDevice == null) {
                        return;
                    }

                    mCaptureSession = session;
                    try {
                        // 开始预览
                        session.setRepeatingRequest(previewRequestBuilder.build(),
                                null, mBackgroundHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                    Log.e("Camera2Preview", "Failed to configure capture session.");
                }
            }, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    // 选择最佳预览尺寸
    private Size chooseBestSize(Size[] sizes) {
        Size defaultSize = new Size(1920, 1080);
        if (sizes == null || sizes.length == 0) {
            return defaultSize;
        }

        // 找到最接近 1080p 的尺寸
        Size bestSize = sizes[0];
        for (Size size : sizes) {
            if (size.getWidth() <= 1920 && size.getHeight() <= 1080) {
                if (size.getWidth() * size.getHeight() >
                        bestSize.getWidth() * bestSize.getHeight()) {
                    bestSize = size;
                }
            }
        }
        return bestSize;
    }

    private void closeCamera() {
        if (mCaptureSession != null) {
            mCaptureSession.close();
            mCaptureSession = null;
        }
        if (mCameraDevice != null) {
            mCameraDevice.close();
            mCameraDevice = null;
        }
    }
}